package pro.cherish.knowledgedemothread.forkjoin;

/**
 * @author 创建人：cherish
 * @version 版本号：V1.0
 * <p>
 * ***************************修订记录************************************
 * 2019-11-10 cherish 创建该类功能。
 * **********************************************************************
 * </p>
 * @ClassName 类名：TestRecursiveAction
 * @Description 功能说明：
 * <p>
 * TODO
 * </p>
 * **********************************************************************
 * @date 创建日期： 2019-11-10 cherish
 */


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;

public class TestRecursiveAction {
    public static void main(String[] args) {
        //ForkJoinPool forkJoinPool = new ForkJoinPool(1);
        //输出永远如下：
		/*
		Splitting workLoad : 24
		ForkJoinPool-1-worker-1  not Splitting and execute : 12
		ForkJoinPool-1-worker-1  not Splitting and execute : 12
		 */
        ForkJoinPool forkJoinPool = new ForkJoinPool(4);
		/*
		输出不定
		Splitting workLoad : 24
		ForkJoinPool-1-worker-1  not Splitting and execute : 12
		ForkJoinPool-1-worker-2  not Splitting and execute : 12
		=================或者
		Splitting workLoad : 24
		ForkJoinPool-1-worker-1  not Splitting and execute : 12
		ForkJoinPool-1-worker-1  not Splitting and execute : 12
		 */
        MyRecursiveAction myRecursiveAction = new MyRecursiveAction(47);
        // MyRecursiveAction myRecursiveAction = new MyRecursiveAction(24);
        forkJoinPool.invoke(myRecursiveAction);
    }
}
class MyRecursiveAction extends RecursiveAction{
    private long workLoad = 0;
    public MyRecursiveAction(long workLoad) {
        this.workLoad = workLoad;
    }
    @Override
    protected void compute() {
        if(this.workLoad>16){
            System.out.println("Splitting workLoad : " + this.workLoad);
            List<MyRecursiveAction> subtasks =
                    new ArrayList<>();
            subtasks.addAll(createSubtasks());
            for(RecursiveAction subtask : subtasks){
                subtask.fork();
            }
        }
        else{
            System.out.println(Thread.currentThread().getName()+"  not Splitting and execute : " + this.workLoad);
        }
    }
    private List<MyRecursiveAction> createSubtasks(){
        List<MyRecursiveAction> subtasks = new ArrayList<>();
        MyRecursiveAction subtask1 = new MyRecursiveAction(this.workLoad/2);
        MyRecursiveAction subtask2 = new MyRecursiveAction(this.workLoad-this.workLoad/2);
        subtasks.add(subtask1);
        subtasks.add(subtask2);
        return subtasks;

    }
}
